home *** CD-ROM | disk | FTP | other *** search
- Path: news.mira.net.au!news
- From: davidw@werple.net.au (David White)
- Newsgroups: comp.lang.c++
- Subject: Re: Strange (to me) notation - little help?
- Date: 4 Jan 1996 19:49:53 +1100
- Organization: Werple Internet, Melbourne
- Message-ID: <4cg4bh$hp1@werple.net.au>
- References: <30EB32AC.2836@sierra.net>
- NNTP-Posting-Host: werple.mira.net.au
-
- "Tyler G. Colwell" <snowbull@sierra.net> writes:
-
- >I am reading Jesse Liberty's "Teach Yourself C++ in 21 Days" and have come across some notation that I can't
- >find explained anywhere. Here is a code fragment of a constructor that he uses in listing 9.4:
-
- >***********************************************
- > class SimpleCat
- > {
- > public:
- > SimpleCat (int age, int weight);
- > ~SimpleCat() {}
- > int GetAge() { return itsAge; }
- > int GetWeight() { return itsWeight; }
- > private:
- > int itsAge;
- > int itsWeight;
- > };
-
- > SimpleCat::SimpleCat(int age, int weight):
- > itsAge(age), itsWeight(weight) {}
- >***********************************************
-
- >Wow, those last two lines are dumbfounding. What is the colon at the end of that one line for, and what's up
- >with using members itsAge and itsWeight as functions in the last line, and howcome none of them are inside the
- >braces?
-
- >Looking forward to some clarification on this one...
-
- The colon introduces the constructor's initializer list, within which you
- can initialize the base class constructor and any member objects. For
- consistency with the initialization syntax used for user-defined types,
- built-in types may use the same syntax, e.g., int x(5) creates an int and
- gives it an initial value of 5. In your example, an initializer list is
- not required; initialization could have been deferred to the c'tor body.
- However, there are many cases in which an initializer list is necessary,
- such as the construction of base class or member objects that do not have
- default constructors, and reference members. For example:
-
- struct A
- { A(int i) { n = i; }
- int n;
- };
-
- struct B : public A
- { B() : A(7) {} //Initializer list required
- };
-
- Class A's constructor must be called before execution enters the body of
- B's constructor, but because A does not have a default constructor, it is
- necessary to provide an initializer list that determines how A's
- constructor should be called.
-
- David White
- davidw@werple.mira.net.au
-
-